// 时间戳的方式
export const throttleByTimestamp = function (func, delay) {
    let prev = Date.now();
    return function () {
        let context = this;
        let args = arguments;
        let now = Date.now();
        if (now - prev >= delay) {
            func.apply(context, args);
            prev = Date.now();
        }
    }
}

//节流(合并)
export const throttle = function (fn, wait = 500, isImmediate = false) {
    let flag = true;
    let timer = null;

    let resultFunc = null;

    if (isImmediate) {
        // 立即执行
        resultFunc = function () {
            if (flag) {
                fn.apply(this, arguments);
                flag = false;
                timer = setTimeout(() => {
                    flag = true
                }, wait)
            }
        }

        resultFunc.cancel = function () {
            console.log("立即取消等待")
            clearTimeout(timer)
        }
    } else {
        // 不立即执行
        resultFunc = function () {

            if (flag == true) {
                flag = false
                timer = setTimeout(() => {
                    fn.apply(this, arguments)
                    flag = true
                }, wait)
            }
        }

        resultFunc.cancel = function () {
            console.log("立即取消等待")
            clearTimeout(timer);
            flag = true;
        }
    }

    return resultFunc;

}

// // 计时器方式
// export const throttle = function(func, delay){
//     let timer = null;

//     return function(){
//         let context = this;
//         let args = arguments;

//         if(!timer){
//             timer = setTimeout(function(){
//                 func.apply(context,args);
//                 timer = null;  
//             }, delay)
//         }
//     }
// }

// 